﻿const express = require('express')
const logger = require('morgan')
const cors = require('cors')
const router = require('./router')
const errorHandler = require('./middleware/error-handler')
const { formatTime } = require('./utils/date')
let FileStreamRotator = require('file-stream-rotator')
let fs = require('fs')
let path = require('path')

require('dotenv').config();

// 连接数据库
require('./model')

const app = express()

let logDirectory = path.join(__dirname, 'log')
fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory)
let accessLogStream = FileStreamRotator.getStream({
    date_format: 'YYYYMMDD',
    filename: path.join(logDirectory, 'access-%DATE%.log'),
    frequency: 'daily',
    verbose: false
})

let errorLogStream = FileStreamRotator.getStream({
    date_format: 'YYYYMMDD', //日期类型
    filename: path.join(logDirectory, '%DATE%-error.log'), //文件名
    frequency: 'daily', //每天的频率
    verbose: false
});
   
// 配置日志输出中间件
// app.use(morgan('dev'))
// 自定义token
logger.token('localDate',function getDate(req) {
    return formatTime()
})

  
// 自定义format，其中包含自定义的token
logger.format('log', '[:localDate] :remote-addr :remote-user :method :url HTTP/:http-version :status :res[content-length] ":referrer"');
logger.format('errLog', 
'[:localDate] :remote-addr :remote-user :method :url HTTP/:http-version :status :res[content-length] ":referrer" ":user-agent"');

app.use(logger('log', {stream: accessLogStream}));
//写访问出错的log日志
app.use(logger('errLog', {
    skip: function (req, res) {
        return res.statusCode < 400
    },
    stream: errorLogStream
}));

// 配置解析请求体
app.use(express.json())
app.use(express.urlencoded())

// 配置跨域
app.use(cors())

// 如果环境变量里有，就默认读取环境变量里的
const PORT = process.env.API_PORT
// 挂载路由
app.use('/xp/api',  router)

// 挂载统一处理服务端错误中间件
app.use(errorHandler())

app.listen(PORT, () => {
    console.log(`数据服务已经启动，端口${PORT}`);
})